package com.czz.portal.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.czz.common.exception.ResultCodeEnum;
import com.czz.common.vo.R;
import com.czz.portal.entity.Study;
import com.czz.portal.service.StudyService;
import com.czz.portal.vo.StudyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;


/**
 * @ClassName: StudyController
 * @Author Czz
 * @Date 2020/2/16
 * @Time 11:43
 **/
@RestController
@RequestMapping(value = "/study")
public class StudyController {

    @Autowired
    StudyService studyService;

    /**
    * @Description 根据课时id获取用户课程学习记录
    * @Param [userId, periodId]
    * @Return com.czz.common.vo.R
    * @Author Czz
    * @Date 2020/2/17
    * @Time 11:06
    **/
    @GetMapping(value = "")
    public R getStudy(@RequestParam String userId,
                      @RequestParam(value = "periodId",required = false) String periodId,
                      @RequestParam(value = "courseId",required = false) String courseId){
        if (StringUtils.isEmpty(userId) || (StringUtils.isEmpty(periodId) && StringUtils.isEmpty(courseId))){
            return R.setResult(ResultCodeEnum.INPUT_ERROR);
        }
        Study study = studyService.getStudy(userId,periodId,courseId);
        if (!ObjectUtils.isEmpty(study)){
            return R.ok().data("item",study);
        }
        return R.setResult(ResultCodeEnum.NOT_FOUND);
    }

    /**
    * @Description 新增或更新学习记录
    * @Param [study]
    * @Return com.czz.common.vo.R
    * @Author Czz
    * @Date 2020/2/17
    * @Time 13:22
    **/
    @PostMapping(value = "")
    public R saveOrUpdateStudy(Study study){
        if (StringUtils.isEmpty(study.getUserId()) || StringUtils.isEmpty(study.getPeriodId())){
            return R.setResult(ResultCodeEnum.INPUT_ERROR);
        }
        studyService.saveOrUpdateStudy(study);
        return R.ok();
    }

    /**
    * @Description 分页查询用户学习记录
    * @Param [page, limit, userId]
    * @Return com.czz.common.vo.R
    * @Author Czz
    * @Date 2020/2/17
    * @Time 13:29
    **/
    @GetMapping(value = "/{page}/{limit}/{userId}")
    public R getStudyPageList(@PathVariable Long page,@PathVariable Long limit,@PathVariable String userId){
        if (page <= 0 || limit <= 0 || StringUtils.isEmpty(userId)){
            return R.setResult(ResultCodeEnum.INPUT_ERROR);
        }
        Page<StudyVo> pageParam = new Page<>(page,limit);
        pageParam.setRecords(studyService.getStudyPageList(pageParam,userId));

        Long total = pageParam.getTotal();
        return R.ok().data("total", total).data("rows", pageParam.getRecords());
    }
}
